package com.duke.shaking.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.content.Context;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Address;
import android.os.Bundle;
import android.util.Log;

public class LocationUtils {
	public static String cityName;    
    public static double latitude;
    public static double longitude;
    
    private static Geocoder geocoder;    
  
    public static void getCityNameByLocation(Context context){    

        geocoder = new Geocoder(context);    
        LocationManager locationManager;     
        String serviceName = Context.LOCATION_SERVICE;     
        locationManager = (LocationManager)context.getSystemService(serviceName);       
        String provider = LocationManager.NETWORK_PROVIDER;    
    
        Criteria criteria = new Criteria();    
        criteria.setAccuracy(Criteria.ACCURACY_FINE);   
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        Location location = locationManager.getLastKnownLocation(provider);
            
        String queryed_name = updateWithNewLocation(location);
        if((queryed_name != null) && (0 != queryed_name.length())){
            cityName = queryed_name;
        }    

        locationManager.requestLocationUpdates(provider, 30000, 50,    
                locationListener);
        locationManager.removeUpdates(locationListener);
    }

    private final static LocationListener locationListener = new LocationListener() {
        String tempCityName;
        public void onLocationChanged(Location location) {
            tempCityName = updateWithNewLocation(location);
            if((tempCityName != null) && (tempCityName.length() != 0)){
                cityName = tempCityName;
                Log.i("shaking", "citiName: " + cityName);
            }
        }

        public void onProviderDisabled(String provider) {
            tempCityName = updateWithNewLocation(null);
            if ((tempCityName != null) && (tempCityName.length() != 0)) {
                cityName = tempCityName;
                Log.i("shaking", "citiName: " + cityName);
            }
        }
    
        public void onProviderEnabled(String provider) {
        }

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
    };
  
    private static String updateWithNewLocation(Location location) {
        String mcityName = "";
        double lat = 0;
        double lng = 0;
        List<Address> addList = null;
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            latitude = lat;
            longitude = lng;
        } else {
            Log.e("shaking", "can't get the location");
        }

        try {   
            addList = geocoder.getFromLocation(lat, lng, 1);                
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        	Log.e("shaking", "can't get location by lat and lng");
        }
        if (addList != null && addList.size() > 0) {
            for (int i = 0; i < addList.size(); i++) {
                Address add = addList.get(i);
                mcityName += add.getLocality();
            }
        }
        
        Log.i("shaking", "got city: " + mcityName);
        if(mcityName.length() != 0){
            return mcityName.substring(0, (mcityName.length() - 1));
        } else {
            return mcityName;
        }
    }
    
    /**  
     * Another way to get the location by latitude and longitude via the google service  
     * @param latitude  
     * @param longitude  
     * @return cityName
     */
    public static String GetAddr(String latitude, String longitude) {
        String addr = "";
            
        /*  
         * we can also use http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s，
  		 * but the result will be english.
         * we can set any value for key, key=abc
         * output=csv, can also be json or xml, here, we use csv format
         */
        String url = String.format(
            "http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
            latitude, longitude);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
          e.printStackTrace();
          return null;
        }
            
        try {

            httpsConn = (URLConnection) myURL.openConnection();

            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(
                        httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null) {
                    String[] retList = data.split(",");
                    if (retList.length > 2 && ("200".equals(retList[0]))) {
                        addr = retList[2];      
                    } else {
                        addr = "";
                    }
                }
                insr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();      
           return null;      
        }
        return addr;
    }

}
